package com.qujia.station.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qujia.common.annotation.Log;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.controller.BaseController;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.domain.ResultData;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.core.page.TableDataInfo;
import com.qujia.common.enums.BusinessType;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.DateUtils;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.ServletUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.common.utils.poi.ExcelUtil;
import com.qujia.customer.domain.CustomerCardUseRecord;
import com.qujia.customer.service.ICustomerCardUseRecordService;
import com.qujia.framework.web.service.TokenService;
import com.qujia.label.domain.CustomerLabelDemo;
import com.qujia.label.domain.SendMessageSelect;
import com.qujia.label.service.ICustomerLabelDemoService;
import com.qujia.label.service.ICustomerLabelService;
import com.qujia.station.domain.*;
import com.qujia.station.domain.dto.SysAppUserInfoExport;
import com.qujia.station.domain.dto.TruckNumberDTO;
import com.qujia.station.domain.vo.EnterpriseAndStationVo;
import com.qujia.station.domain.vo.appUserNumberVo;
import com.qujia.station.enums.SexFlagEnum;
import com.qujia.station.service.IAppUserInfoService;
import com.qujia.station.service.IEnterpriseService;
import com.qujia.station.service.IStationService;
import com.qujia.station.utils.IdempotentUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 油站信息Controller
 *
 * @author qujia
 * @date 2020-12-08
 */
@Api(tags = "会员信息")
@RestController
@RequestMapping("/appUserInfo/info")
@Slf4j
public class AppUserInfoController extends BaseController {
    @Autowired
    private IAppUserInfoService appUserInfoService;
    @Autowired
    private IStationService stationService;
    @Autowired
    private ICustomerCardUseRecordService customerCardUseRecordService;
    @Autowired
    private IEnterpriseService enterpriseService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ICustomerLabelDemoService customerLabelDemoService;
    @Autowired
    private ICustomerLabelService customerLabelService;
    @Autowired
    private IdempotentUtil idempotentUtil;


    @PostMapping("/increaseShareCount")
    @ApiOperation(value = "增加分享次数", notes = "根据用户ID增加分享次数")
    public void increaseShareCount(@RequestParam("userId") Long userId) {
        try {
            appUserInfoService.increaseShareCount(userId);
        } catch (Exception e) {
            e.printStackTrace();
            // Handle the exception as needed
        }
    }


    @PostMapping("/increaseTruckNumber")
    @ApiOperation(value = "编辑车牌号", notes = "编辑车牌号")
    public void increaseTruckNumber(@RequestBody TruckNumberDTO truckNumberDTO) {
        try {
            appUserInfoService.increaseTruckNumber(truckNumberDTO.getTruckNumber(), truckNumberDTO.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            // Handle the exception as needed
        }
    }

    @GetMapping("/getShareCount")
    @ApiOperation(value = "获取分享次数", notes = "根据用户ID获取分享次数")
    public Integer getShareCountByUserId(@RequestParam("userId") Long userId) {
        try {
            Integer count = appUserInfoService.getShareCountByUserId(userId);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            // Handle the exception as needed
            return null; // Return an appropriate value or throw a custom exception
        }
    }

    /**
     * 查询会员信息列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "查询会员信息列表", notes = "查询会员信息列表")
    public TableDataInfo list(SysAppUserInfo appUserInfo) {
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            appUserInfo.setStationId(current.getUser().getEnterpriseId());
        } else if ("2".equals(current.getUser().getUserLevel())) {
            if (current.getUser().getStationId() != null) {
                Station station = stationService.selectStationById(current.getUser().getStationId());
                appUserInfo.setStationId(station.getEnterpriseId());
            }
        } else if (SecurityUtils.isPartner()) {
            EnterpriseAndStationVo itemIds = stationService.getItemIds(current.getUser());
            if (itemIds != null){
                if(CollectionUtils.isEmpty(itemIds.getEnterpriseIds())){
                    return getDataTable(new ArrayList<>());
                }
                appUserInfo.setEnterpriseIdListForAuthor(itemIds.getEnterpriseIds());
            } else {
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
        }
        startPage();
        List<SysAppUserInfo> memberList = appUserInfoService.selectAppUserInfoList(appUserInfo);
        return getDataTable(memberList);
    }


    /**
     * 导出会员信息列表
     */
    @GetMapping("/exportList")
    @ApiOperation(value = "导出会员信息列表", notes = "导出会员信息列表")
    public AjaxResult exportList(SysAppUserInfo appUserInfo) {
        // 只有admin 有权限导出会员信息
        if (Objects.isNull(appUserInfo) || Objects.isNull(appUserInfo.getStationId())) {
            return AjaxResult.error("请先选择油企");
        }

        List<SysAppUserInfoExport> memberList = appUserInfoService.selectAppUserInfoList(appUserInfo)
                .stream().map(sysAppUserInfo -> {
                    if (Objects.nonNull(sysAppUserInfo)) {
                        SysAppUserInfoExport sysAppUserInfoExport = new SysAppUserInfoExport();
                        BeanUtils.copyProperties(sysAppUserInfo, sysAppUserInfoExport);
                        if (Objects.nonNull(sysAppUserInfo.getRegisteDate())) {
                            sysAppUserInfoExport.setRegisteDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, sysAppUserInfo.getRegisteDate()));
                        } else {
                            sysAppUserInfoExport.setRegisteDate("");
                        }
                        sysAppUserInfoExport.setSexFlag(SexFlagEnum.getSexFlag(sysAppUserInfo.getSexFlag()));
                        return sysAppUserInfoExport;
                    }
                    return null;
                }).collect(Collectors.toList());
        ExcelUtil<SysAppUserInfoExport> util = new ExcelUtil<SysAppUserInfoExport>(SysAppUserInfoExport.class);
        return util.exportExcel(memberList, getName(appUserInfo.getStationId()));
    }

    // 定制化文件文件名
    private String getName(Long enterpriseId) {
        String name = "";
        Enterprise enterprise = enterpriseService.selectEnterpriseById(enterpriseId);
        name = getDateSign() + enterprise.getEnterpriseName() + "会员信息";
        return name;
    }

    // 获取当前时间 2023年10月30日
    private String getDateSign() {
        return DateUtils.parseDateToStr("yyyy年MM月dd日", new Date());
    }


    /**
     * 手动发券查询会员信息列表
     */
    @GetMapping("/listForCoupon")
    @ApiOperation(value = "手动发券查询会员信息列表", notes = "手动发券查询会员信息列表")
    public TableDataInfo listForCoupon(CustomerLabelDemo customerLabelDemo) {
        LoginUser current = SecurityUtils.getLoginUser();
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();

        if ("1".equals(current.getUser().getUserLevel())) {
            customerLabelDemo.setStationId(current.getUser().getEnterpriseId());
        } else if ("2".equals(current.getUser().getUserLevel())) {
            if (current.getUser().getStationId() != null) {
                Station station = stationService.selectStationById(current.getUser().getStationId());
                customerLabelDemo.setStationId(station.getEnterpriseId());
            }
        }else if(SecurityUtils.isPartner()){
            EnterpriseAndStationVo itemIds = stationService.getItemIds(currentUser.getUser());
            List<Long> enterpriseIds = itemIds.getEnterpriseIds();
            if (enterpriseIds != null && enterpriseIds.size()>0) {
                customerLabelDemo.setEnterpriseIdListForAuthor(enterpriseIds);
            } else {
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
        }
        startPage();
        List<CustomerLabelDemo> memberList = appUserInfoService.selectAppUserInfoListForCoupon(customerLabelDemo);
        return getDataTable(memberList);
    }

    /**
     * 获取会员信息详细信息
     */
    @GetMapping(value = "/selectAppUserInfoSum")
    public AjaxResult selectAppUserInfoSum(SysAppUserInfo appUserInfo) {
        SysAppUserInfo appUserInfo1 = appUserInfoService.selectAppUserInfoSum(appUserInfo);
        return AjaxResult.success(appUserInfo1);
    }

    /**
     * 新增会员
     */
    @Log(title = "增加会员", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysAppUserInfo appUserInfo) {
        String format = new SimpleDateFormat("yyMMdd").format(new Date()) + RandomStringUtils.randomNumeric(5);
        appUserInfo.setMemberCode(format);
        appUserInfo.setRegisteDate(new Date());
        return toAjax(appUserInfoService.insertAppUserInfo(appUserInfo));
    }

    /**
     * 新增会员
     */
    @Log(title = "修改会员积分", businessType = BusinessType.INSERT)
    @PostMapping(value = "/addAppUserPoints")
    public AjaxResult addAppUserPoints(@RequestBody SysAppUserInfo appUserInfo) {
        return toAjax(appUserInfoService.addAppUserPoints(appUserInfo));
    }

    /**
     * 发送模针对用户
     */
    @Log(title = "推送会员消息", businessType = BusinessType.INSERT)
    @PostMapping(value = "/sendMessageToUser")
    public ResultData sendMessageToUser(@RequestBody SendMessage sendMessage) {
        LoginUser current = SecurityUtils.getLoginUser();
        Enterprise enterprise = enterpriseService.selectEnterpriseById(current.getUser().getEnterpriseId());
        sendMessage.setEnterpriseName(enterprise.getEnterpriseName());
        return appUserInfoService.sendMessageToUserNew(sendMessage);

    }

    /**
     * 发送模针对用户
     */
    @Log(title = "推送会员消息", businessType = BusinessType.INSERT)
    @PostMapping(value = "/sendMessageToUserBatch")
    public ResultData sendMessageToUserBatch(@RequestBody CustomerLabelDemo customerLabelDemo) {
        return appUserInfoService.sendMessageToUserBatch(customerLabelDemo);

    }

    /**
     * 发送模针对用户
     */
    @Log(title = "向云华发送用户", businessType = BusinessType.INSERT)
    @PostMapping(value = "/sendUserToYunHua")
    public AjaxResult sendUserToYunHua(@RequestBody SysAppUserInfo sysAppUserInfo) {
        int mmm = appUserInfoService.sendUserToYunHua(sysAppUserInfo);
        return AjaxResult.success(mmm);
    }

    /**
     * 主动发卷
     */
    @PostMapping(value = "/activeSendMessage")
    public AjaxResult activeSendMessage(@RequestBody ActiveSendCoupon activeSendCoupon) {
//        if(enterprise.getEnterpriseId()!=null) {
//            Enterprise enterprise1 = enterpriseService.selectEnterpriseById(enterprise.getEnterpriseId());
//            if (enterprise1.getCardId()!=null) {
//               return AjaxResult.error("当前油企以获取卡卷，不可重新获取");
//            }
//        }
        int success = 0;
        int fail = 0;
        LoginUser current = SecurityUtils.getLoginUser();
        if (!current.getUser().getUserLevel().equals("1")) {
            return AjaxResult.error("非油企用户不得使用发放功能");
        }
        Enterprise enterprise = enterpriseService.selectEnterpriseById(current.getUser().getEnterpriseId());
        if (activeSendCoupon.getCodeList() == null || activeSendCoupon.getCodeList().size() <= 0) {
            return AjaxResult.error("没有查询到订单信息");
        }
        for (String code : activeSendCoupon.getCodeList()) {
            SysAppUserInfo sysAppUserInfo = new SysAppUserInfo();
            sysAppUserInfo.setCardCode(code);
            sysAppUserInfo.setStationId(current.getUser().getEnterpriseId());
            List<SysAppUserInfo> appUserInfos = appUserInfoService.selectAppUserInfoList(sysAppUserInfo);
            if (appUserInfos != null && appUserInfos.size() > 0 && appUserInfos.get(0).getBlogOpenid() != null) {
                int falg = enterpriseService.push(appUserInfos.get(0).getBlogOpenid(), enterprise, activeSendCoupon.getUrl(), activeSendCoupon.getMessage(), activeSendCoupon);
                if (falg == 1) {
                    success++;
                } else {
                    fail++;
                }
            } else {
                fail++;
            }
        }
        if (success == 0) {
            return AjaxResult.error("发送失败，请联系管理员");
        }
        return AjaxResult.success("成功人数" + success + "   失败人数" + fail);
    }

    /**
     * 根据已知的条件进行筛选
     */
    @PostMapping(value = "/selectSendMessage")
    public AjaxResult selectSendMessage(@RequestBody SendMessageSelect sendMessageSelect) {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SendMessage sendMessage = new SendMessage();
        Enterprise enterprise = enterpriseService.selectEnterpriseById(currentUser.getUser().getEnterpriseId());
        //时间转化的
        Format f = new SimpleDateFormat("yyyy-MM-dd");
        if ("1".equals(sendMessageSelect.getType())) {
            List<SysAppUserInfo> sysAppUserInfoUsers = appUserInfoService.selectNewAppUser(currentUser.getUser().getEnterpriseId());
            if (sysAppUserInfoUsers == null || sysAppUserInfoUsers.size() == 0) {
                return AjaxResult.error("没有新用户信息");
            }
            List<String> code = new ArrayList<>();
            sendMessage.setMessage(sendMessageSelect.getMessage());
            for (SysAppUserInfo sysAppUserInfo : sysAppUserInfoUsers) {
                code.add(sysAppUserInfo.getBlogOpenid());
            }
            sendMessage.setOpenIdList(code);
            return appUserInfoService.sendMessageToUser(sendMessage, enterprise);

        } else if ("2".equals(sendMessageSelect.getType())) {
            List<String> code = new ArrayList<>();
            if (sendMessageSelect.getDay() == null) {
                return AjaxResult.error("传入的天数为空");
            }
            Long endT = System.currentTimeMillis();

            Long startTs = endT - Long.parseLong(String.valueOf((Long.parseLong(sendMessageSelect.getDay() + "") * Long.parseLong(86400000 + ""))));

            CustomerLabelDemo customerLabelDemo = new CustomerLabelDemo();
            customerLabelDemo.setAmtFlag("1");
            customerLabelDemo.setLitersFlag("1");
            customerLabelDemo.setSecondFlag("0");
            customerLabelDemo.setBeginDate(f.format(startTs));
            customerLabelDemo.setEndDate(f.format(endT));
            customerLabelDemo.setSecondAmtFlag("1");
            customerLabelDemo.setLitersFlag("1");

            List<CustomerLabelDemo> customerLabelDemoList = customerLabelDemoService.selectCustomerLabelDemoList(customerLabelDemo);
            if (customerLabelDemoList == null || customerLabelDemoList.size() <= 0) {
                return AjaxResult.success("没有当前条件的用户");
            }
            for (CustomerLabelDemo customerLabelDemo1 : customerLabelDemoList) {
                code.add(customerLabelDemo1.getBlogOpenid());
            }
            sendMessage.setMessage(sendMessageSelect.getMessage());
            sendMessage.setOpenIdList(code);
            return appUserInfoService.sendMessageToUser(sendMessage, enterprise);

        } else if ("3".equals(sendMessageSelect.getType())) {
            List<String> code = new ArrayList<>();
            if (sendMessageSelect.getDay() == null) {
                return AjaxResult.error("传入的天数为空");
            }
            Long endT = System.currentTimeMillis();
            Long startTs = endT - sendMessageSelect.getDay() * 24 * 60 * 60 * 1000;

            CustomerLabelDemo customerLabelDemo = new CustomerLabelDemo();
            customerLabelDemo.setAmtFlag("1");
            customerLabelDemo.setLitersFlag("1");
            customerLabelDemo.setSecondFlag("1");
            customerLabelDemo.setSecondBeginDate(f.format(startTs));
            customerLabelDemo.setSecondEndDate(f.format(endT));
            customerLabelDemo.setSecondEndCountNum(0);
            customerLabelDemo.setSecondAmtFlag("1");
            customerLabelDemo.setLitersFlag("1");

            List<CustomerLabelDemo> customerLabelDemoList = customerLabelDemoService.secondCustomerLabelDemoList(customerLabelDemo);
            if (customerLabelDemoList == null || customerLabelDemoList.size() <= 0) {
                return AjaxResult.success("没有当前条件的用户");
            }
            for (CustomerLabelDemo customerLabelDemo1 : customerLabelDemoList) {
                code.add(customerLabelDemo1.getBlogOpenid());
            }
            sendMessage.setMessage(sendMessageSelect.getMessage());
            sendMessage.setOpenIdList(code);
            return appUserInfoService.sendMessageToUser(sendMessage, enterprise);

        } else if ("4".equals(sendMessageSelect.getType())) {
            List<String> code = new ArrayList<>();
            if (sendMessageSelect.getDay() == null) {
                return AjaxResult.error("传入的天数为空");
            }

            if (sendMessageSelect.getAmount() == null) {
                return AjaxResult.error("传入的金额为空");
            }
            Long endT = System.currentTimeMillis();
            Long startTs = endT - sendMessageSelect.getDay() * 24 * 60 * 60 * 1000;

            CustomerLabelDemo customerLabelDemo = new CustomerLabelDemo();
            customerLabelDemo.setAmtFlag("1");
            customerLabelDemo.setLitersFlag("1");
            customerLabelDemo.setSecondFlag("0");
            customerLabelDemo.setBeginDate(f.format(startTs));
            customerLabelDemo.setEndDate(f.format(endT));
            customerLabelDemo.setSecondEndCountNum(0);
            customerLabelDemo.setSecondAmtFlag("1");
            customerLabelDemo.setLitersFlag("1");
            customerLabelDemo.setStartAmt(sendMessageSelect.getAmount());

            List<CustomerLabelDemo> customerLabelDemoList = customerLabelDemoService.selectCustomerLabelDemoList(customerLabelDemo);
            if (customerLabelDemoList == null || customerLabelDemoList.size() <= 0) {
                return AjaxResult.success("没有当前条件的用户");
            }
            for (CustomerLabelDemo customerLabelDemo1 : customerLabelDemoList) {
                code.add(customerLabelDemo1.getBlogOpenid());
            }
            sendMessage.setMessage(sendMessageSelect.getMessage());
            sendMessage.setOpenIdList(code);
            return appUserInfoService.sendMessageToUser(sendMessage, enterprise);

        } else if ("5".equals(sendMessageSelect.getType())) {
            List<String> code = new ArrayList<>();
            if (sendMessageSelect.getDay() == null) {
                return AjaxResult.error("传入的天数为空");
            }

            if (sendMessageSelect.getAmount() == null) {
                return AjaxResult.error("传入的金额为空");
            }
            Long endT = System.currentTimeMillis();
            Long startTs = endT - sendMessageSelect.getDay() * 24 * 60 * 60 * 1000;

            CustomerLabelDemo customerLabelDemo = new CustomerLabelDemo();
            customerLabelDemo.setAmtFlag("1");
            customerLabelDemo.setLitersFlag("1");
            customerLabelDemo.setSecondFlag("0");
            customerLabelDemo.setBeginDate(f.format(startTs));
            customerLabelDemo.setEndDate(f.format(endT));
            customerLabelDemo.setSecondEndCountNum(0);
            customerLabelDemo.setSecondAmtFlag("1");
            customerLabelDemo.setLitersFlag("1");
            customerLabelDemo.setEndAmt(sendMessageSelect.getAmount());

            List<CustomerLabelDemo> customerLabelDemoList = customerLabelDemoService.selectCustomerLabelDemoList(customerLabelDemo);
            if (customerLabelDemoList == null || customerLabelDemoList.size() <= 0) {
                return AjaxResult.success("没有当前条件的用户");
            }
            for (CustomerLabelDemo customerLabelDemo1 : customerLabelDemoList) {
                code.add(customerLabelDemo1.getBlogOpenid());
            }
            sendMessage.setMessage(sendMessageSelect.getMessage());
            sendMessage.setOpenIdList(code);
            return appUserInfoService.sendMessageToUser(sendMessage, enterprise);

        } else if ("6".equals(sendMessageSelect.getType())) {
            List<String> code = new ArrayList<>();
            if (sendMessageSelect.getDay() == null) {
                return AjaxResult.error("传入的天数为空");
            }

            if (sendMessageSelect.getCount() == null) {
                return AjaxResult.error("传入的次数为空");
            }
            Long endT = System.currentTimeMillis();
            Long startTs = endT - sendMessageSelect.getDay() * 24 * 60 * 60 * 1000;

            CustomerLabelDemo customerLabelDemo = new CustomerLabelDemo();
            customerLabelDemo.setAmtFlag("1");
            customerLabelDemo.setLitersFlag("1");
            customerLabelDemo.setSecondFlag("0");
            customerLabelDemo.setBeginDate(f.format(startTs));
            customerLabelDemo.setEndDate(f.format(endT));
            customerLabelDemo.setSecondEndCountNum(0);
            customerLabelDemo.setSecondAmtFlag("1");
            customerLabelDemo.setLitersFlag("1");
            customerLabelDemo.setStartCountNum(sendMessageSelect.getCount());

            List<CustomerLabelDemo> customerLabelDemoList = customerLabelDemoService.selectCustomerLabelDemoList(customerLabelDemo);
            if (customerLabelDemoList == null || customerLabelDemoList.size() <= 0) {
                return AjaxResult.success("没有当前条件的用户");
            }
            for (CustomerLabelDemo customerLabelDemo1 : customerLabelDemoList) {
                code.add(customerLabelDemo1.getBlogOpenid());
            }
            sendMessage.setMessage(sendMessageSelect.getMessage());
            sendMessage.setOpenIdList(code);
            return appUserInfoService.sendMessageToUser(sendMessage, enterprise);
        } else if ("7".equals(sendMessageSelect.getType())) {
            List<String> code = new ArrayList<>();
            if (sendMessageSelect.getDay() == null) {
                return AjaxResult.error("传入的天数为空");
            }

            if (sendMessageSelect.getCount() == null) {
                return AjaxResult.error("传入的次数为空");
            }
            Long endT = System.currentTimeMillis();
            Long startTs = endT - sendMessageSelect.getDay() * 24 * 60 * 60 * 1000;

            CustomerLabelDemo customerLabelDemo = new CustomerLabelDemo();
            customerLabelDemo.setAmtFlag("1");
            customerLabelDemo.setLitersFlag("1");
            customerLabelDemo.setSecondFlag("0");
            customerLabelDemo.setBeginDate(f.format(startTs));
            customerLabelDemo.setEndDate(f.format(endT));
            customerLabelDemo.setSecondEndCountNum(0);
            customerLabelDemo.setSecondAmtFlag("1");
            customerLabelDemo.setLitersFlag("1");
            customerLabelDemo.setEndCountNum(sendMessageSelect.getCount());

            List<CustomerLabelDemo> customerLabelDemoList = customerLabelDemoService.selectCustomerLabelDemoList(customerLabelDemo);
            if (customerLabelDemoList == null || customerLabelDemoList.size() <= 0) {
                return AjaxResult.success("没有当前条件的用户");
            }
            for (CustomerLabelDemo customerLabelDemo1 : customerLabelDemoList) {
                code.add(customerLabelDemo1.getBlogOpenid());
            }
            sendMessage.setMessage(sendMessageSelect.getMessage());
            sendMessage.setOpenIdList(code);
            return appUserInfoService.sendMessageToUser(sendMessage, enterprise);
        } else if ("8".equals(sendMessageSelect.getType())) {
            List<String> code = new ArrayList<>();
            if (sendMessageSelect.getDay() == null) {
                return AjaxResult.error("传入的天数为空");
            }
            if (sendMessageSelect.getAmount() == null) {
                return AjaxResult.error("传入的金额为空");
            }
            Long endT = System.currentTimeMillis();
            Long startTs = endT - sendMessageSelect.getDay() * 24 * 60 * 60 * 1000;

            CustomerLabelDemo customerLabelDemo = new CustomerLabelDemo();
            customerLabelDemo.setAmtFlag("2");
            customerLabelDemo.setLitersFlag("1");
            customerLabelDemo.setSecondFlag("1");
            customerLabelDemo.setStartAmt(sendMessageSelect.getAmount());
            customerLabelDemo.setSecondBeginDate(f.format(startTs));
            customerLabelDemo.setSecondEndDate(f.format(endT));
            customerLabelDemo.setSecondEndCountNum(0);
            customerLabelDemo.setSecondAmtFlag("1");
            customerLabelDemo.setLitersFlag("1");

            List<CustomerLabelDemo> customerLabelDemoList = customerLabelDemoService.secondCustomerLabelDemoList(customerLabelDemo);
            if (customerLabelDemoList == null || customerLabelDemoList.size() <= 0) {
                return AjaxResult.success("没有当前条件的用户");
            }
            for (CustomerLabelDemo customerLabelDemo1 : customerLabelDemoList) {
                code.add(customerLabelDemo1.getBlogOpenid());
            }
            sendMessage.setMessage(sendMessageSelect.getMessage());
            sendMessage.setOpenIdList(code);
            return appUserInfoService.sendMessageToUser(sendMessage, enterprise);

        } else if ("0".equals(sendMessageSelect.getType())) {
            SysAppUserInfo sysAppUserInfo = new SysAppUserInfo();
            sysAppUserInfo.setStationId(currentUser.getUser().getEnterpriseId());
            sysAppUserInfo.setCodeFalg("1");
            List<SysAppUserInfo> sysAppUserInfoUsers = appUserInfoService.selectAppUserInfoList(sysAppUserInfo);
            if (sysAppUserInfoUsers == null || sysAppUserInfoUsers.size() <= 0) {
                return AjaxResult.success("没有用户信息");
            }
            List<String> code = new ArrayList<>();
            for (SysAppUserInfo sysAppUserInfo1 : sysAppUserInfoUsers) {
                if (sysAppUserInfo1.getCardCode() != null && !"".equals(sysAppUserInfo1.getCardCode())) {
                    code.add(sysAppUserInfo1.getBlogOpenid());
                }

            }
            sendMessage.setMessage(sendMessageSelect.getMessage());
            sendMessage.setOpenIdList(code);
            return appUserInfoService.sendMessageToUser(sendMessage, enterprise);

        }
        return AjaxResult.error("未查询到用户信息");
    }

    /**
     * 清除redis缓存信息
     */
    @Log(title = "清除redis缓存信息", businessType = BusinessType.INSERT)
    @PostMapping(value = "/clearAppId")
    public AjaxResult clearAppId() {
        LoginUser current = SecurityUtils.getLoginUser();
        Enterprise enterprise = enterpriseService.selectEnterpriseById(current.getUser().getEnterpriseId());
        return appUserInfoService.clearRedis(enterprise);

    }

    /**
     * 查询客户电子会员卡充值消费记录列表
     */
    @GetMapping("/listUseRecordByAppUserInfo")
    public TableDataInfo listUseRecordByAppUserInfo(SysAppUserInfo appUserInfo) {
        LoginUser current = SecurityUtils.getLoginUser();
        CustomerCardUseRecord customerCardUseRecord = new CustomerCardUseRecord();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            if(stations==null||stations.size()==0){
                List<CustomerCardUseRecord> recordList = new ArrayList<>();
                return getDataTable(recordList);
            }
            List<String> stationids = new ArrayList<>();
            for (Station station1 : stations) {
                stationids.add(station1.getStationId() + "");
            }
            customerCardUseRecord.setStationIdList(stationids);
        } else if ("2".equals(current.getUser().getUserLevel())) {
            customerCardUseRecord.setStationId(current.getUser().getStationId().intValue());
        }
        customerCardUseRecord.setMobilePhone(appUserInfo.getMobilePhone());
        customerCardUseRecord.setStatus("1");
        customerCardUseRecord.setUsageType("+");
        startPage();
        List<CustomerCardUseRecord> recordList = customerCardUseRecordService.selectCustomerCardUseRecordList(customerCardUseRecord);
        return getDataTable(recordList);
    }

    /**
     * 导出会员列表
     */
    @Log(title = "会员信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SysAppUserInfo appUserInfo) {
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            appUserInfo.setStationId(current.getUser().getEnterpriseId());
        } else if ("2".equals(current.getUser().getUserLevel())) {
            if (current.getUser().getStationId() != null) {
                Station station = stationService.selectStationById(current.getUser().getStationId());
                appUserInfo.setStationId(station.getEnterpriseId());
            }
        }
        List<SysAppUserInfo> memberList = appUserInfoService.selectAppUserInfoList(appUserInfo);
        ExcelUtil<SysAppUserInfo> util = new ExcelUtil<SysAppUserInfo>(SysAppUserInfo.class);
        return util.exportExcel(memberList, "order");
    }

    @Log(title = "用户导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        if (file == null || file.isEmpty()) {
            return AjaxResult.error("上传的文件不能为空");
        }
        ExcelUtil<AppUserInfoExcel> util = new ExcelUtil<AppUserInfoExcel>(AppUserInfoExcel.class);
        List<AppUserInfoExcel> appuserListExcel = util.importExcel(file.getInputStream());
        Date date = new Date();

        LocalDateTime currentDateTime = LocalDateTime.now();
        Instant instant = currentDateTime.atZone(ZoneId.systemDefault()).toInstant();
        Date date2 = Date.from(instant);
        List<SysAppUserInfo> appuserList = new ArrayList<>();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());

//       long enterpriseId= loginUser.getUser().getEnterpriseId();
        for (AppUserInfoExcel appuserexcel : appuserListExcel) {
            if (appuserexcel == null) {
                return AjaxResult.error("Excel表不能为空");
            }
            appuserexcel.setMobilePhone(StringUtils.trim(appuserexcel.getMobilePhone()));
            // 检查手机号是否为空
            if (StringUtils.isBlank(appuserexcel.getMobilePhone()) || appuserexcel.getMobilePhone() == null) {
                return AjaxResult.error("手机号不能为空");
            }
            // 检查会员编码
            if (ObjectUtils.isEmpty(appuserexcel.getMemberCode())) {
                return AjaxResult.error("会员编码不能为空");
            }
            // 检查手机号格式是否正确
            String mobilePhone = appuserexcel.getMobilePhone();
            if (!Pattern.matches("^1[0-9]{10}$", mobilePhone)) {
                return AjaxResult.error("手机号格式不正确");
            }
            // 检查站点ID是否为空
            if (appuserexcel.getStationId() == null || appuserexcel.getStationId() == 0) {
                return AjaxResult.error("油企ID不能为空");
            }
            if (loginUser.getUser() != null && loginUser.getUser().getUserLevel() == null) {

            } else {
                if (loginUser.getUser().getUserLevel().equals("2")) {
                    return AjaxResult.error("油站无用户导入权限");
                }
                if (loginUser.getUser().getEnterpriseId() != null
                        && !loginUser.getUser().getEnterpriseId().equals(0L)
                        && !loginUser.getUser().getEnterpriseId().equals(appuserexcel.getStationId())) {
                    return AjaxResult.error("油企ID不能是非本油企ID");
                }
            }
            SysAppUserInfo sysAppUserInfo = new SysAppUserInfo(); //
            sysAppUserInfo.setMemberCode(appuserexcel.getMemberCode());
            sysAppUserInfo.setBirthday(appuserexcel.getBirthday());
            sysAppUserInfo.setBlogNickName(appuserexcel.getBlogNickName());
            sysAppUserInfo.setMobilePhone(appuserexcel.getMobilePhone());
            sysAppUserInfo.setName(appuserexcel.getName());
            sysAppUserInfo.setStationId(appuserexcel.getStationId());
            sysAppUserInfo.setCreateTime(date);
            sysAppUserInfo.setRegisteDate(date);
            String sexFlag = appuserexcel.getSexFlag();
            if (sexFlag != null) {
                if ("男".equals(sexFlag)) {
                    sysAppUserInfo.setSexFlag("M");
                } else if ("女".equals(sexFlag)) {
                    sysAppUserInfo.setSexFlag("W");
                } else {
                    sysAppUserInfo.setSexFlag("");
                }
            } else {
                sysAppUserInfo.setSexFlag("");
            }
            sysAppUserInfo.setTruckNumber(appuserexcel.getTruckNumber());
            sysAppUserInfo.setIntegral(appuserexcel.getIntegral());

            //如果是老用户覆盖 不更新注册时间
            if (null != appuserexcel.getMobilePhone() && !appuserexcel.getMobilePhone().isEmpty() && null != appuserexcel.getStationId()) {
                // 验证是否已注册的老用户
                SysAppUserInfo appUserInfoByPhoneAndStationId = appUserInfoService.getUserRegisteDateByPhoneAndStationId(appuserexcel.getMobilePhone(), appuserexcel.getStationId());
                if (ObjectUtils.isNotEmpty(appUserInfoByPhoneAndStationId)) {
                    Date registeDate = appUserInfoByPhoneAndStationId.getRegisteDate();
                    sysAppUserInfo.setRegisteDate(registeDate);
                }
            }


            appuserList.add(sysAppUserInfo);
        }
        String operName = loginUser.getUsername();
        String message = appUserInfoService.importAppUserInfo(appuserList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    /**
     * 获取导出会员信息模板
     */
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<AppUserInfoExcel> util = new ExcelUtil<AppUserInfoExcel>(AppUserInfoExcel.class);
        return util.importTemplateExcel("会员信息");
    }

    /**
     * 获取会员信息详细信息
     */
    @GetMapping(value = "/{appUserInfoId}")
    public AjaxResult getInfo(@PathVariable("appUserInfoId") Long appUserInfoId) {
        SysAppUserInfo appUserInfo = appUserInfoService.selectAppUserInfoById(appUserInfoId);

        return AjaxResult.success(appUserInfo);
    }

    /**
     * 修改会员信息
     */
    @Log(title = "会员信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysAppUserInfo appUserInfo) {

        return toAjax(appUserInfoService.updateMember(appUserInfo));
    }

    @GetMapping("/getAppUserNumber")
    @ApiOperation(value = "获取会员数量")
    public appUserNumberVo getAppUserNumber(@ApiParam(value = "开始时间") @RequestParam(value = "beginTime", required = false) String beginTime,
                                            @ApiParam(value = "结束时间") @RequestParam(value = "endTime", required = false) String endTime) {

        LoginUser current = SecurityUtils.getLoginUser();

        SysAppUserInfo appUserInfo = new SysAppUserInfo();

        if ("1".equals(current.getUser().getUserLevel())) {
            appUserInfo.setStationId(current.getUser().getEnterpriseId());
        } else if ("2".equals(current.getUser().getUserLevel())) {
            if (current.getUser().getStationId() != null) {
                Station station = stationService.selectStationById(current.getUser().getStationId());
                appUserInfo.setStationId(station.getEnterpriseId());
            }
        }else if (SecurityUtils.isPartner()) {
            EnterpriseAndStationVo itemIds = stationService.getItemIds(current.getUser());
            if (itemIds != null){
                if(CollectionUtils.isEmpty(itemIds.getEnterpriseIds())){
                    return new appUserNumberVo();
                }
                appUserInfo.setEnterpriseIdListForAuthor(itemIds.getEnterpriseIds());
            } else {
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
        }
        appUserInfo.setBeginTime(beginTime);
        appUserInfo.setEndTime(endTime);
        return appUserInfoService.getAppUserNumber(appUserInfo);
    }

    @PostMapping("/updateUserMemberCode")
    @ApiOperation(value = "给会员编码为空的会员生成会员编码", notes = "给会员编码为空的会员生成会员编码")
    public AjaxResult updateUserMemberCode(@ApiParam(value = "油企id") @RequestParam(value = "enterpriseId") Long enterpriseId) {
        String key = IdempotentUtil.GenerateKey("updateUserMemberCode", String.valueOf(enterpriseId));
        if (!idempotentUtil.tryLock(key)) {
            log.error("/updateUserMemberCode接口频繁请求，time:{}", System.currentTimeMillis());
            throw new CustomException("请勿重复刷新同一油企");
        }

        appUserInfoService.updateUserMemberCode(enterpriseId);

        return AjaxResult.success();
    }

    @GetMapping("restPassword")
    @ApiOperation("充值会员支付密码")
    public ResultData restAppUserPassword(@ApiParam("会员userId") @RequestParam Long userId) {
        appUserInfoService.restAppUserPassword(userId);
        return ResultData.success();
    }

    /**
     * 重置用户 openId ，其实就是将用户的 openId 置空
     *
     * @param userId
     * @return
     */
    @GetMapping("/updateOpenId/{userId}")
    public AjaxResult updateOpenId(@PathVariable("userId") Long userId) {
        if (appUserInfoService.updateOpenId(userId)) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

}
